<!--
 * @Author: 赵宇
 * @Description: 
 * @Date: 2023-04-17 15:15:31
 * @LastEditTime: 2023-04-26 16:54:06
 * @LastEditors: pancc 527847805@qq.com
 * @FilePath: \pcj\src\page\order\components\buyTable.vue
-->
<template>
  <ul class="flow-page-header">
    <li>产品明细</li>
    <li>
      <el-button v-if="!disabled" size="small" type="primary" @click="onProductAdd()">添加</el-button>
      <el-button v-if="!disabled" size="small" type="primary" @click="status.bulkShow = true">产品库</el-button>
      <columnSetting v-model="props.column" size="small" name="orderBuyEdit/GetProductList" />
    </li>
  </ul>
  <el-table :data="table.data" class="flexible-table" border stripe tooltip-effect @header-dragend="headerDragend">
    <el-table-column type="index" label="序号" align="center" width="60" />
    <el-table-column
      v-for="(item, index) in props.column.filter(r => r.show)"
      :width="item.width"
      :min-width="item.minWidth"
      :prop="item.id"
      :label="item.label"
      :key="item.id + index"
      show-overflow-tooltip
      align="center"
    >
      <template #default="scope">
        <!-- 操作 -->
        <template v-if="item.id === 'operate'">
          <z-button icon="xiugai" size="small" title="编辑" @click="onEdit(scope.row)" v-if="purview(3)"></z-button>
          <z-button icon="delete" type="danger" size="small" title="删除" @click="onDel([scope.row.id])" v-if="purview(4)"></z-button>
        </template>
        <!-- 图片 -->
        <el-image style="width: 60px; height: 60px" :src="scope.row[item.id]" fit="cover" v-else-if="item.id === 'imagePath'" :disabled="disabled"  />
        <!-- 价格 -->
        <template v-else-if="['price', 'number'].includes(item.id)">
          <z-input v-model="scope.row[item.id]" @change="onInputChange(scope.row)" :disabled="disabled"></z-input>
        </template>
        <!-- 仓库 -->
        <z-select
          v-else-if="item.id === 'whInfoId'"
          v-model="scope.row[item.id]"
          clearable
          class="w-100"
          api="WhInfo/GetList"
          :apiParams="{ statusId: 1 }"
          placeholder="请选择仓库"
          :disabled="disabled" 
        ></z-select>
        <!-- 仓位 -->
        <z-select
          v-else-if="item.id === 'whInfoStorageId'"
          v-model="scope.row[item.id]"
          clearable
          class="w-100"
          api="WhInfo/GetList"
          :disabled="!scope.row.whInfoId"
          :apiParams="{ statusId: 1, whInfoId: scope.row.whInfoId }"
          placeholder="请选择仓位"
        ></z-select>
        <!-- 税率 -->
        <z-select
          v-else-if="item.id === 'taxRate'"
          v-model="scope.row[item.id]"
          clearable
          class="w-100"
          api="DictionaryValue/GetPage"
          :apiParams="{ dictionaryType: 5 }" 
          placeholder="请选择税率"
          @change="val => onTaxRateChange(val, scope.row)"
          isReturnObj 
        ></z-select>

        <template v-else>
          {{ scope.row[item.id] }}
        </template>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加编辑产品 -->
  <orderBuyProductEdit v-model="status.show" @onSave="onSaveCallback" :editData="status.editData" />

  <!-- 产品库选择产品 -->
  <productDialog v-model="status.bulkShow" @onSave="onProductCallback" />
</template>
<script setup>
import productDialog from 'page/product/components/productDialog.vue';
import orderBuyProductEdit from './orderBuyProductEdit.vue';
import { post } from '@/api/index.js';
import { watch } from 'vue';
let route = useRoute();
let router = useRouter();
let { purview, numTransform } = inject('$global');
let message = inject('$message');
let table = reactive({
  data: [],
  column: []
});
let emits = defineEmits(['update:column']);
let props = defineProps({
  modelValue: {
    type: Array,
    default: () => {
      return [];
    }
  },
  column: {
    type: Array,
    default: () => {
      return [];
    }
  },
  isTax: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
});
watch(
  () => props.modelValue,
  async val => {
    table.data = val;
  },
  {
    immediate: true
  }
);
// 单独处理 含税
watch(
  () => props.isTax,
  async val => {
    let rows = props.column.map(r => {
      if (['taxRate', 'taxAmount'].includes(r.id)) {
        r.show = val;
      }
      return r;
    });
    emits('update:column', rows);
    // 单独处理含税
    if (val) {
      table.data.map(val => {
        let total = numTransform(val.price * val.number);
        let taxAmount = numTransform((total * parseFloat(val.taxRate ? val.taxRateLabel : 0)) / 100);
        val.taxAmount = taxAmount;
        val.totalAmount = numTransform(total - taxAmount);
      });
    } else {
      table.data.map(val => {
        val.taxRate = null;
        val.taxRateLabel = '';
        let total = numTransform(val.price * val.number);
        val.taxAmount = 0;
        val.totalAmount = total;
      });
    }
  },
  {
    immediate: true
  }
);
let status = reactive({
  bulkShow: false,
  editData: {},
  show: false
});
// 添加产品
let onProductAdd = () => {
  status.editData = {};
  status.show = true;
};

const onProductCallback = vals => {
  vals.map(r => {
    let val = {
      ...r,
      productId: r.id,
      number: r.number || 0,
      baseNumber: 0,
      baseUnit: r.unit,
      basePrice: r.price,
      taxAmount: 0,
      totalAmount: 0,
      baseAmount: 0
    };
    val.totalAmount = numTransform(val.price * val.number);
    table.data.push(val);
  });
};
// 拖动表头触发
const headerDragend = async (newWidth, oldWidth, columns) => {
  let index = props.column.findIndex(r => r.id === columns.property);
  let column = [...props.column];
  let row = column[index];
  if (row.minWidth) row.minWidth = newWidth;
  if (row.width) row.width = newWidth;
  saveProductList(column);
};
// 存储产品表头
const saveProductList = async val => {
  await post('ColumnSetting/CreateOrUpdate', {
    id: 0,
    interfaceName: 'orderBuyEdit/GetProductList',
    columnJson: JSON.stringify(val)
  });
};
// 单价 数量 change
const onInputChange = val => {
  let total = numTransform(val.price * val.number);
  let taxAmount = 0;
  if (props.isTax && val.taxRateLabel) {
    taxAmount = numTransform((total * parseFloat(val.taxRateLabel)) / 100);
  }
  val.taxAmount = taxAmount;
  val.totalAmount = numTransform(total - taxAmount);
};
// 税率
const onTaxRateChange = (row, val) => {
  let total = numTransform(val.price * val.number);
  let taxAmount = numTransform((total * parseFloat(row.label)) / 100);
  val.taxAmount = taxAmount;
  val.taxRateLabel = row.label;
  val.totalAmount = numTransform(total - taxAmount);
};
// 验证
const check = async () => {
  if (!table.data.length) return false;
  // 如果是含税的
  if (props.isTax) {
    let index = table.data.findIndex(r => !r.taxRate);
    if (index != null) {
      message.warning(`第${index + 1}项商品，${table.data[index].productName} 税率未选择!`);
      return;
    }
  }
  // 单独处理一些参数
  return table.data.map(r => {
    return {
      ...r,
      ...{
        whInfoId: r.whInfoId || 0,
        whInfoStorageId: r.whInfoStorageId || 0,
        taxRate: r.taxRate || 0
      }
    };
  });
};
defineExpose({
  check
});
</script>
<style lang="scss" scoped>
.flow-page-header {
  margin-top: 20px;
  width: 100%;
  background-color: #a8ebad;
  display: flex;
  justify-content: space-between;
  height: 40px;
  line-height: 40px;
  padding: 0px 10px;
}
</style>
